package cn.nfwx.tv.helper;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;

import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.RequestExecutor;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.nfwx.tv.activity.HomeActivity;
import cn.nfwx.tv.base.BaseActivity;
import cn.nfwx.tv.base.NFWXApplication;
import cn.nfwx.tv.conts.Constants;
import cn.nfwx.tv.events.PlayLiveEvents;
import cn.nfwx.tv.fragment.dialog.WifiConnectDialogFragment;
import cn.nfwx.tv.fragment.dialog.WifiDialogFragment;
import cn.nfwx.tv.fragment.dialog.WifiNoteFragment;
import cn.nfwx.tv.manager.NFWXWiFiManager;
import cn.nfwx.tv.okhttp.CustomOkHttpClient;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.NetworkUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by dell on 2018/1/19.
 */

public class WifiHelper {

    private static final String TAG = WifiHelper.class.getSimpleName();

    private static WifiHelper instance;

    private List<String> mWifis = new ArrayList<>();

    private Set<Wifi> wifiList = new HashSet<>();

    boolean _isConnect = false;
    boolean _isShowSuccess = false;
    boolean _isShowFalure = false;

    public static WifiHelper getInstance() {
        if (instance == null) {
            instance = new WifiHelper();
        }
        return instance;
    }

    public static final int WIFI_STATUS_INIT = -1;
    public static final int WIFI_STATUS_ENABLE = 1;
    public static final int WIFI_STATUS_DISABLE = 2;

    public static class Wifi {
        public String wifi;
        public int status;

        Wifi(String wifi, int status) {
            this.wifi = wifi;
            this.status = status;
        }
    }

    public void clearData() {
        wifiList.clear();
    }

    public void setData(List<String> wifis) {
        mWifis.clear();
        mWifis.addAll(wifis);
        for (String string : wifis) {
            boolean isHas = false;
            for (Wifi wifi : wifiList) {
                if (wifi.wifi.contains(string)) {
                    isHas = true;
                    break;
                }
            }
            if (!isHas) {
                wifiList.add(new Wifi(string, WIFI_STATUS_INIT));
            }
        }

        for (Wifi wifi : wifiList) {
            if (wifi.status == WIFI_STATUS_INIT) {
                _isConnect = false;
                connentWifi(wifi);
                break;
            }
        }
    }

    public List<String> getWifis() {
        return mWifis;
    }

    /**
     * wifi自动链接地址
     *
     * @return
     */
    private static String getWifiUrl() {
        StringBuilder builder = new StringBuilder(Constants.test_url);
        builder.append("/nfwx-wifi/v1");
        return builder.toString();
    }

    /**
     * 开启检索，定时任务操作
     *
     * @param context
     */
    public static void initialize(Context context) {
        String url = getWifiUrl();
        //NFWXWiFiManager.initialize(context, url);
    }

    /**
     * 启动wifi扫描动作
     */
    public static void startScan(NFWXWiFiManager.OnWiFiAvailableListener cb) {
        LogUtil.d(TAG, "startScan");
        MobclickAgent.onEvent(NFWXApplication.getInstance(), TAG, "startScan");
//        NFWXWiFiManager.getInstance().removeOnWiFiAvailableListener(null);
//        NFWXWiFiManager.getInstance().addOnWiFiAvailableListener(cb);
//        WifiHelper.getInstance().clearData();
//        NFWXWiFiManager.getInstance().start();
    }

    /**
     * 停止WIFI扫描
     */
    public static void stopScan() {
        MobclickAgent.onEvent(NFWXApplication.getInstance(), TAG, "stopScan");
//        if (NFWXApplication.getInstance() != null) {
//            NFWXWiFiManager.getInstance().removeOnWiFiAvailableListener(null);
//            NFWXWiFiManager.getInstance().stop();
//        }
    }

    /**
     * 遍历wifi判断状态
     */
    public void connentWifi(final Wifi wifi) {
        if (_isConnect) return;
        _isConnect = true;
        final BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
        if (activity == null) {
            return;
        }
        if (activity instanceof HomeActivity) {
            if (AccountHelper.getInstance().isLogin(activity)) { //已经登录直接登入验证WIFI
                final WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance();
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiConnectDialogFragment);
                String accessToken = AccountHelper.getInstance().getAccessToken(activity);
                final NFWXWiFiManager.OnWiFiEnabled onWiFiEnabled = new NFWXWiFiManager.OnWiFiEnabled() {
                    @Override
                    public void onEnabled() {
                        _isConnect = false;
                        if (ActivityHelper.getInstance().hasActivity()) {
                            BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
                            final WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance(2);
                            DialogFragmentHelper.closeLoadingDialog(activity.getSupportFragmentManager());
                            DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiConnectDialogFragment);
                            wifiConnectDialogFragment.setSureListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    wifiConnectDialogFragment.dismissAllowingStateLoss();
                                }
                            });
                            wifi.status = WIFI_STATUS_ENABLE;
                        }

                        stopScan();
                    }

                    @Override
                    public void onFailed(String msg) {
                        _isConnect = false;
                        wifi.status = WIFI_STATUS_DISABLE;
                        boolean isEnd = true;
                        for (Wifi wifi : wifiList) {
                            if (wifi.status == WIFI_STATUS_INIT) {
                                connentWifi(wifi);
                                isEnd = false;
                            }
                        }
                        if (isEnd) {
                            if (ActivityHelper.getInstance().hasActivity()) {
                                BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
                                DialogFragmentHelper.closeLoadingDialog(activity.getSupportFragmentManager());
                                WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance(3);
                                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiConnectDialogFragment);
                                wifiConnectDialogFragment.setTryMoreListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        connentWifi(wifi);
                                    }
                                });
                            }
                        }
                    }
                };

                wifiConnectDialogFragment.setSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        wifiConnectDialogFragment.dismissAllowingStateLoss();
                    }
                });

                wifiConnectDialogFragment.setTryMoreListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        connentWifi(wifi);
                    }
                });

                NFWXWiFiManager.getInstance().connect(wifi.wifi, accessToken, onWiFiEnabled);
            } else { // 没有登录弹出登录界面
                final WifiDialogFragment wifiDialogFragment = WifiDialogFragment.newInstance(true);
                wifiDialogFragment.setPositiveListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //MineActivity.startActivity(activity, 0);
                        wifiDialogFragment.dismiss();
                    }
                });
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiDialogFragment);
            }
        }
    }

    /**
     * 遍历wifi判断状态
     */
    public void connentWifi(final String wifi) {
        if (_isConnect) return;
        _isConnect = true;
        mWifis.clear();
        mWifis.add(wifi);
        final BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
        if (activity == null) {
            return;
        }
        if (activity instanceof HomeActivity) {
            if (AccountHelper.getInstance().isLogin(activity)) { //已经登录直接登入验证WIFI
                final WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance();
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiConnectDialogFragment);
                String accessToken = AccountHelper.getInstance().getAccessToken(activity);
                final NFWXWiFiManager.OnWiFiEnabled onWiFiEnabled = new NFWXWiFiManager.OnWiFiEnabled() {
                    @Override
                    public void onEnabled() {
                        _isConnect = false;
                        _isShowSuccess = true;

                        // 在后台无法弹出提示框
                        if (!ActivityHelper.getInstance().isBackground() && ActivityHelper.getInstance().hasActivity()) {
                            final BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
                            final WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance(2);
                            DialogFragmentHelper.closeLoadingDialog(activity.getSupportFragmentManager());
                            DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiConnectDialogFragment);
                            wifiConnectDialogFragment.setSureListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    _isShowSuccess = false;
                                    wifiConnectDialogFragment.dismissAllowingStateLoss();
                                    String lid = SharePrefUtil.getLiveId(activity);
                                    EventBus.getDefault().post(new PlayLiveEvents(lid, ""));
                                }
                            });
                            stopScan();
                        }
                    }

                    @Override
                    public void onFailed(String msg) {
                        _isConnect = false;
                        _isShowFalure = true;
                        if (!ActivityHelper.getInstance().isBackground() && ActivityHelper.getInstance().hasActivity()) {
                            BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
                            DialogFragmentHelper.closeLoadingDialog(activity.getSupportFragmentManager());
                            WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance(3);
                            DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiConnectDialogFragment);
                            wifiConnectDialogFragment.setTryMoreListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    _isShowFalure = false;
                                    connentWifi(wifi);
                                }
                            });
                        }


                    }
                };

                wifiConnectDialogFragment.setSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        wifiConnectDialogFragment.dismissAllowingStateLoss();
                        String lid = SharePrefUtil.getLiveId(activity);
                        EventBus.getDefault().post(new PlayLiveEvents(lid, ""));
                    }
                });

                wifiConnectDialogFragment.setTryMoreListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        disconnect();
                        connentWifi(wifi);
                    }
                });

                NFWXWiFiManager.getInstance().connect(wifi, accessToken, onWiFiEnabled);
            } else { // 没有登录弹出登录界面
                final WifiDialogFragment wifiDialogFragment = WifiDialogFragment.newInstance(true);
                wifiDialogFragment.setPositiveListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //MineActivity.startActivity(activity, 0);
                        wifiDialogFragment.dismiss();
                    }
                });
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiDialogFragment);
            }
        }
    }

    /**
     * 登录不成功
     */
    public void disconnect() {
        _isConnect = false;
    }

    /**
     * 检测是否能上内网认证
     */
    public void checkAuthWifi(final ValueCallback<Boolean> callback) {
        CustomOkHttpClient.cancleAll("checkAuthWifi");
        CustomOkHttpClient.doGet(getWifiUrl() + "list", "checkAuthWifi", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onReceiveValue(false);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() != 200) {
                    callback.onReceiveValue(false);
                } else {
                    callback.onReceiveValue(true);
                }
            }
        });
    }

    /**
     * 测试是否能上外网
     */
    public void _testIfNeedLogon(final ValueCallback<Boolean> callback, String requestCode) {
        CustomOkHttpClient.doGet("http://www.baidu.com", requestCode, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onReceiveValue(false);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 204 || response.code() == 200) {
                    callback.onReceiveValue(true);
                } else {
                    callback.onReceiveValue(false);
                }
            }
        });
    }

    /**
     * 所连接的Wifi是否可以，不可以开启扫描
     *
     * @param activity
     * @param executor
     */
    public void checkWifi(final Activity activity, RequestExecutor executor) {
        if (NetworkUtil.isWifiConnection(activity)) {
            // 防止内存泄漏
            WifiHandler wifiHandler = new WifiHandler(activity, executor);
            final Handler handler = new Handler(Looper.getMainLooper(), wifiHandler);
            CustomOkHttpClient.cancleAll("_testIfNeedLogon");
            _testIfNeedLogon(new ValueCallback<Boolean>() {
                @Override
                public void onReceiveValue(Boolean value) {
                    if (value) { // 可以上网
                        return;
                    } else { // 不能上网
                        checkAuthWifi(new ValueCallback<Boolean>() {
                            @Override
                            public void onReceiveValue(Boolean value) {
                                if (value) {
                                    if (!ActivityHelper.getInstance().isBackground()) {
                                        Activity activity1 = ActivityHelper.getInstance().getCurrentActivity();
                                        WifiManager mgr = (WifiManager) activity1.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                                        if (mgr != null && mgr.isWifiEnabled()) {
                                            WifiInfo info = mgr.getConnectionInfo();
                                            String ssid = info.getSSID().replace("\"", "");
                                            mWifis.clear();
                                            mWifis.add(ssid);
                                            handler.sendEmptyMessage(1); // 检测可以上内网
                                        } else {
                                            handler.sendEmptyMessage(0); // 检测不可以上内网
                                        }
                                    }
                                } else {
                                    handler.sendEmptyMessage(0); // 检测不可以上内网
                                }
                            }
                        });
                    }
                }
            }, "checkWifi");
        }
    }

    /**
     * 所链接Wi-Fi是否
     *
     * @param context
     */
    public void checkWifiResume(Context context) {
        if (NetworkUtil.isWifiConnection(context)) {
            CustomOkHttpClient.cancleAll("checkWifiResume");
            _testIfNeedLogon(new ValueCallback<Boolean>() {
                @Override
                public void onReceiveValue(Boolean value) {
                    if (value) { // 可以上网
                        Activity activity = ActivityHelper.getInstance().getCurrentActivity();
                        if (activity != null && activity instanceof BaseActivity) {
                            FragmentManager fragmentManager = ((BaseActivity) activity).getSupportFragmentManager();
                            Fragment wifiFragment = DialogFragmentHelper.getFragment(fragmentManager, WifiDialogFragment.class.getName());
                            if (wifiFragment != null && wifiFragment instanceof WifiDialogFragment) {
                                ((WifiDialogFragment) wifiFragment).dismissAllowingStateLoss();
                            }

                            Fragment connectFragment = DialogFragmentHelper.getFragment(fragmentManager, WifiConnectDialogFragment.class.getName());
                            if (connectFragment != null && connectFragment instanceof WifiConnectDialogFragment) {
                                ((WifiConnectDialogFragment) connectFragment).dismissAllowingStateLoss();
                            }

                            Fragment noteFragment = DialogFragmentHelper.getFragment(fragmentManager, WifiNoteFragment.class.getName());
                            if (noteFragment != null && noteFragment instanceof WifiNoteFragment) {
                                ((WifiNoteFragment) noteFragment).dismissAllowingStateLoss();
                            }
                        }
                    }
                }
            }, "checkWifiResume");
        }
    }

    /**
     * 回调写好，防止activity强制保留在内存中，无法销毁，造成内存泄漏
     */
    private class WifiHandler implements Handler.Callback, NFWXWiFiManager.OnWiFiEnabled {
        private WeakReference<Activity> activityWeakReference;
        private WeakReference<RequestExecutor> rationaleListenerWeakReference;

        public WifiHandler(Activity activity, RequestExecutor rationaleListener) {
            activityWeakReference = new WeakReference<Activity>(activity);
            rationaleListenerWeakReference = new WeakReference<RequestExecutor>(rationaleListener);
        }

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) { // 外网上不了
                final Activity activity = activityWeakReference.get();
                final RequestExecutor rationaleListener = rationaleListenerWeakReference.get();
                if (activity != null && rationaleListener != null) {
                    DialogFragmentHelper.showConfirmDialog(((BaseActivity) activity).getSupportFragmentManager(), null, "您现在链接的" + NetworkUtil.getWifiSSID(activity) + "Wi-Fi无法上网,搜索附近的免费Wi-Fi", "好的", "取消", true, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            PermissionHelper.getInstance().requestWifiPerission(activity, new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> data) {

                                }
                            }, new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> data) {

                                }
                            });
                        }
                    }, null);
                }
            } else if (msg.what == 1) { // 可以上内网
                final Activity activity = activityWeakReference.get();
                if (activity instanceof HomeActivity) {
                    if (AccountHelper.getInstance().isLogin(activity)) { //已经登录直接登入验证WIFI
                        WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance();
                        DialogFragmentHelper.showDialogFragment(((BaseActivity) activity).getSupportFragmentManager(), wifiConnectDialogFragment);
                        String accessToken = AccountHelper.getInstance().getAccessToken(activity);
                        WifiManager mgr = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                        if (mgr != null && mgr.isWifiEnabled()) {
                            WifiInfo info = mgr.getConnectionInfo();
                            final String ssid = info.getSSID().replace("\"", "");
                            wifiConnectDialogFragment.setSureListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (!ActivityHelper.getInstance().isBackground()) {
                                        BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
                                        WifiConnectDialogFragment wifiConnectDialogFragment = (WifiConnectDialogFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), WifiConnectDialogFragment.class.getName());
                                        if (wifiConnectDialogFragment != null)
                                            wifiConnectDialogFragment.dismissAllowingStateLoss();
                                    }
                                    String lid = SharePrefUtil.getLiveId(activity);
                                    EventBus.getDefault().post(new PlayLiveEvents(lid, ""));
                                }
                            });

                            wifiConnectDialogFragment.setTryMoreListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (!ActivityHelper.getInstance().isBackground()) {
                                        BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
                                        WifiConnectDialogFragment wifiConnectDialogFragment = (WifiConnectDialogFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), WifiConnectDialogFragment.class.getName());
                                        if (wifiConnectDialogFragment != null)
                                            wifiConnectDialogFragment.loadLoading();
                                        String accessToken = AccountHelper.getInstance().getAccessToken(activity);
                                        NFWXWiFiManager.getInstance().connect(ssid, accessToken, WifiHandler.this);
                                    }
                                }
                            });

                            NFWXWiFiManager.getInstance().connect(ssid, accessToken, WifiHandler.this);
                        }

                    } else { // 没有登录弹出登录界面
                        final WifiDialogFragment wifiDialogFragment = WifiDialogFragment.newInstance(true);
                        wifiDialogFragment.setPositiveListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //MineActivity.startActivity(activity, 0);
                                wifiDialogFragment.dismiss();
                            }
                        });
                        DialogFragmentHelper.showDialogFragment(((BaseActivity) activity).getSupportFragmentManager(), wifiDialogFragment);
                    }
                }
            }
            return false;
        }

        @Override
        public void onEnabled() {
            if (!ActivityHelper.getInstance().isBackground() && ActivityHelper.getInstance().hasActivity()) {
                final BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
                final WifiConnectDialogFragment wifiConnectDialogFragment = WifiConnectDialogFragment.newInstance(2);
                DialogFragmentHelper.closeLoadingDialog(activity.getSupportFragmentManager());
                DialogFragmentHelper.showDialogFragment(activity.getSupportFragmentManager(), wifiConnectDialogFragment);
                wifiConnectDialogFragment.setSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        wifiConnectDialogFragment.dismissAllowingStateLoss();
                        String lid = SharePrefUtil.getLiveId(activity);
                        EventBus.getDefault().post(new PlayLiveEvents(lid, ""));
                    }
                });
                stopScan();
            }
        }

        @Override
        public void onFailed(String msg) {
//            if (msg.contains("AUTH")) {
//                NFWXApplication.getInstance().refreshTokenData(new FinishListener() {
//                    @Override
//                    public void onFinish() {
//                        if (ActivityHelper.getInstance().hasActivity()) {
//                            BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
//                            WifiManager mgr = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//                            if (mgr != null && mgr.isWifiEnabled()) {
//                                WifiInfo info = mgr.getConnectionInfo();
//                                String ssid = info.getSSID().replace("\"", "");
//                                String accessToken = AccountHelper.getInstance().getAccessToken(activity);
//                                NFWXWiFiManager.getInstance().connect(ssid, accessToken, WifiHandler.this);
//                            }
//                        }
//                    }
//                });
//            } else {
//                if (!ActivityHelper.getInstance().isBackground()) {
//                    BaseActivity activity = (BaseActivity) ActivityHelper.getInstance().getCurrentActivity();
//                    WifiConnectDialogFragment wifiConnectDialogFragment = (WifiConnectDialogFragment) DialogFragmentHelper.getFragment(activity.getSupportFragmentManager(), WifiConnectDialogFragment.class.getName());
//                    if (wifiConnectDialogFragment != null)
//                        wifiConnectDialogFragment.loadFailure();
//                }
//            }
        }
    }

    public void clearWifiDialogStatus() {
        _isShowFalure = false;
        _isShowSuccess = false;
    }

    public boolean isShowWifiDialogSuccess() {
        return _isShowSuccess;
    }

    public boolean isShowWifiDialogFalure() {
        return _isShowFalure;
    }
}
